<?php
/**
 * PhpStorm
 * User: zucheng
 * Date: 2019/3/24
 */

namespace App\Http\Controllers\Api\V1;

use App\Library\Common;
use App\Models\MemberRelation;
use App\Services\MemberService;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Mockery\Exception;
use Validator;
use App\Http\Controllers\Api\ApiController;
use App\Models\Member;
use Illuminate\Http\Request;

class MemberController extends ApiController
{
    /**
     * 获取员工列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'owner_uuid' => 'required|size:36',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $owner = Member::where('uuid', $request->get('owner_uuid'))->firstOrFail();

            // 获取数据
            $fields = [
                'v_members.id',
                'name',
                'uuid as user_uuid',
                'phone as mobile',
                'v_member_relation.role_id',
                'avatar',
                'status',
            ];
            $query  = Member::leftJoin('v_member_relation', 'v_member_relation.member_id', 'v_members.id')
                ->select($fields)
                ->where('v_member_relation.parent_id', $owner->id);

            // 用户类型
            if ($request->has('user_type')) {
                $types = explode(',', $request->get('user_type'));
                $query->where(function ($query) use ($types) {
                    $query->where('id', '>', 0);
                    foreach ($types as $type) {
                        $query->orWhere('v_member_relation.role_id', 'like', $type);
                    }
                });
            }

            //用户手机号
            if ($request->has('mobile')) {
                $phone = $request->get('mobile');
                $query->where(function ($query) use ($phone) {
                    $query->where('phone', $phone);
                });
            }
            $user = $query->get()->toArray();

            return $this->success('success', $user);
        } catch (ModelNotFoundException $e) {
            return $this->error(Common::notFoundModelFormat($e->getModel()));
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 新增会员/员工
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addMember(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'owner_uuid'    => 'required|size:36',
                'name'          => 'required',
                'mobile'        => 'required|numeric|regex:/^1[3456789][0-9]{9}$/',
                'user_type'     => 'required',
                'relation_type' => 'required',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            $name         = $request->get('name');
            $mobile       = trim($request->get('mobile'));
            $relationType = $request->get('relation_type');

            // 收货人|发货人
            if ($relationType == Member::RELATION_TYPE_DAY) {
                $user = $this->addDayMember($name, $mobile); //添加会员
            } else {
                $user = $this->addFormalMember($request);
            }

            return $this->success('添加成功', [
                'user_uuid' => $user->uuid,
                'name'      => $user->name
            ]);
        } catch (ModelNotFoundException $e) {
            return $this->error(Common::notFoundModelFormat($e->getModel()));
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 编辑员工
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editMember(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'owner_uuid' => 'required|size:36',
                'user_uuid'  => 'required|size:36',
                'name'       => 'required',
                'mobile'     => 'required|numeric|regex:/^1[3456789][0-9]{9}$/',
                'user_type'  => 'required',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $owner  = Member::where('uuid', $request->get('owner_uuid'))->firstOrFail();
            $member = Member::where('uuid', $request->get('user_uuid'))->firstOrFail();
            if ($owner->role_id != Member::ROLE_OWNER) {
                throw new \Exception('只有货主才有添加员工的权限');
            }

            // 手机号验证
            $otherOwner = Member::where('phone', $request->get('mobile'))->first();
            if ($otherOwner && $otherOwner->id != $member->id) {
                throw new \Exception('手机号已被其他用户使用');
            }

            // 编辑员工
            $userType = $request->get('user_type');
            $userType = str_replace('，', ',', $userType);

            // 角色验证
            $arrUserType = explode(',', $userType);
            foreach ($arrUserType as $item) {
                if (!in_array($item, Member::USABLE_ROLE)) {
                    throw new \Exception('找不到需要的用户类型');
                }
            }

            $member->phone = $request->get('mobile');
            !empty($request->get('name', '')) && $member->name = $request->get('name');
            $member->save();

            MemberRelation::where('parent_id', $owner->id)
                ->where('member_id', $member->id)
                ->update([
                    'role_id' => $userType
                ]);

            return $this->success('编辑成功');
        } catch (ModelNotFoundException $e) {
            return $this->error(Common::notFoundModelFormat($e->getModel()));
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 解绑和雇主的关系
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function unbindRelation(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_uuid' => 'required|size:36',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $member = Member::query()
                ->where('uuid', $request->get('user_uuid'))
                ->first();
            if (empty($member)) {
                return $this->error('找不到指定的用户');
            }
            if (in_array($member->role_id, [Member::ROLE_OWNER, Member::ROLE_DRIVER])) {
                return $this->error('货主无此操作权限');
            }
            MemberRelation::where('member_id', $member->id)->delete();

            return $this->success('success');
        } catch (ModelNotFoundException $e) {
            return $this->error(Common::notFoundModelFormat($e->getModel()));
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 添加正式员工
     * @param Request $request
     * @return object $user
     * @throws \Exception
     */
    private function addFormalMember(Request $request)
    {
        $ownerUuid = $request->get('owner_uuid');
        $name      = $request->get('name');
        $mobile    = trim($request->get('mobile'));
        $userType  = $request->get('user_type');
        $userType  = str_replace('，', ',', $userType);

        // 货主判断
        $owner = Member::where('uuid', $ownerUuid)->firstOrFail();
        if ($owner->role_id != Member::ROLE_OWNER) {
            throw new \Exception('只有货主才有添加员工的权限');
        }

        // 角色验证
        $arrUserType = explode(',', $userType);
        foreach ($arrUserType as $item) {
            if (!in_array($item, Member::USABLE_ROLE)) {
                throw new \Exception('找不到需要的用户类型');
            }
        }

        // 唯一性判断
        $user = Member::where('phone', $mobile)->first();
        if (!empty($user)) {
            // 不是普通用户 直接报错
            $roleDsc = Member::$roleDsc;
            if ($user->role_id != 0) {
                throw new \Exception(sprintf('手机号已被注册为%s', $roleDsc[ $user->role_id ]));
            }

            // 货主唯一性判断
            $relationOther = MemberRelation::where('member_id', $user->id)
                ->where('parent_id', '!=', $owner->id)
                ->first();
            if (!empty($relationOther)) {
                throw new Exception('此用户已经是其他公司雇员，请先解除后再添加.');
            }

            $relation = MemberRelation::where('parent_id', $owner->id)
                ->where('member_id', $user->id)
                ->first();
            if (empty($relation)) {
                // 新建关联信息
                MemberRelation::create([
                    'parent_id' => $owner->id,
                    'member_id' => $user->id,
                    'role_id'   => $userType,
                ]);
            }
        } else {
            // 添加员工
            $user = MemberService::getInstance()->addGeneralMember($owner->id, $mobile, $name, $userType);
        }

        return $user;
    }

    /**
     * 添加临时会员
     * @param $name 会员名称
     * @param $phone 会员手机号
     * @return mixed
     */
    private function addDayMember($name, $phone)
    {
        $member = Member::where('phone', $phone)->first();
        if (!$member) {
            $member = Member::create([
                'phone'   => $phone,
                'name'    => $name,
                'uuid'    => \Faker\Provider\Uuid::uuid(),
                'role_id' => 0, //普通员工
            ]);
        }

        return $member;
    }
}